<script lang="ts" setup>
import _ from 'lodash';
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import CheckForUpdates from 'src/components/CheckForUpdates.vue';
import useLoginInfoStore from 'src/stores/useLoginInfoStore';
import getAppVersion from 'src/utils/version';
import Rcs2WebSocket from 'src/runtime/Rcs2WebSocket';
import useRcs2AgvStore from '../stores/useRcs2AgvStore';
import NativeFunction from '../utils/NativeFunction';

const rcs2AgvStore = useRcs2AgvStore();
const router = useRouter();
const route = useRoute();
const $q = useQuasar();
const { locale, t } = useI18n();
const loginInfoStore = useLoginInfoStore();
const showUpdatesDialog = ref(false);
const activeTab = ref(null);
const rcs2WebSocket = new Rcs2WebSocket();

onMounted(async () => {
  rcs2WebSocket.startListener();
});

onUnmounted(() => {
  rcs2WebSocket.stopListener();
});

// 语言列表配置
const languageList = [
  { code: 'zh-CN', label: '中文' },
  { code: 'en-US', label: 'English' }
];

// 检查更新
function checkForUpdates() {
  // 显示版本检查对话框
  showUpdatesDialog.value = true;
}

function handleToggleLeftMenu() {
  LCC.emit('toggleLeftMenu');
}

// 服务器地址 - 从登录信息中获取，默认使用示例地址
const serverUrl = computed(() => 'http://' + loginInfoStore.loginInfo.rcs2ServerUrl);

// 计算属性
const currentLocale = computed(() => locale.value);

watch(activeTab, (activeTab) => {
  if (activeTab === 'rcs2') {
    if (!_.startsWith(route.path, '/rt/rcs2')) {
      router.replace('/rt/rcs2');
    }

  } else if (activeTab === 'agvList') {
    if (!_.startsWith(route.path, '/rt/agvList')) {
      router.replace('/rt/agvList');
    }
  }
});

watch(() => route.path, (path) => {
  if (_.startsWith(path, '/rt/rcs2') || path == '/rt') {
    activeTab.value = 'rcs2';

  } else if (_.startsWith(path, '/rt/agvList')) {
    activeTab.value = 'agvList';
  }

}, { immediate: true });

// 切换语言
function changeLanguage(lang: string) {
  locale.value = lang;
}

function refresh() {
  try {
    NativeFunction.reloadWeb().finally();
  } catch (err) {
    LCC.showErrorDialog('没有发现安卓或桌面环境');
    setTimeout(() => {
      window.location.reload();
    }, 5000);
  }
}

// 全屏模式文本
const fullscreenText = computed(() => {
  return $q.fullscreen.isActive ? t('exitFullscreen') : t('fullscreenMode');
});

// 全屏模式切换
function toggleFullscreen() {
  if ($q.fullscreen.isActive) {
    // 退出全屏模式
    $q.fullscreen.exit()
      .then(() => {
        LCC.msg(t('exitedFullscreen'), { type: 'info' });
      })
      .catch(err => {
        // 退出全屏失败
        LCC.msg(t('exitFullscreenFailed') + ': ' + err, { type: 'error' });
      });
  } else {
    // 请求全屏模式
    $q.fullscreen.request()
      .then(() => {
        // 成功进入全屏
        LCC.msg(t('enteredFullscreen', { type: 'info' }));
      })
      .catch(err => {
        // 进入全屏失败
        LCC.msg(t('enterFullscreenFailed') + ': ' + err, { type: 'error' });
      });
  }
}

// 退出登录
function logout() {
  $q.dialog({
    title: t('rt.confirmLogout'),
    message: t('rt.confirmLogoutMessage'),
    ok: {
      label: t('rt.logout'),
      color: 'negative'
    },
    cancel: {
      label: t('cancel'),
      flat: true
    }
  }).onOk(() => {
    // 清除登录状态
    localStorage.removeItem('rcs2_server_url');
    localStorage.removeItem('rcs2_username');
    // 跳转到登录页
    router.push('/login');
  });
}

</script>
<template>
  <q-layout view="lHh Lpr lFf">
    <!-- 头部工具栏 -->
    <q-header elevated class="text-white yv-header-bg">
      <q-toolbar>
        <q-btn flat dense round icon="menu" @click="handleToggleLeftMenu" />
        <q-toolbar-title style="flex:unset;">{{ t('rt.title') }}</q-toolbar-title>
        <!-- 顶部页签 -->
        <q-tabs v-model="activeTab" class="text-amber-13 yv-header-tab" shrink>
          <q-tab name="rcs2" :label="t('rt.rcs2')" />
          <q-tab name="agvList" :label="t('rt.agvList')" />
        </q-tabs>

        <q-toolbar-title style="text-align: center">{{ route.params.ip }}</q-toolbar-title>

        <!-- 语言切换下拉框-->
        <q-btn-dropdown flat color="amber-12" icon="language" class="language-btn">
          <q-list>
            <q-item v-for="lang in languageList" :key="lang.code" clickable v-close-popup
                    @click="changeLanguage(lang.code)">
              <q-item-section>
                <q-item-label>{{ lang.label }}</q-item-label>
              </q-item-section>
              <q-item-section side>
                <q-icon name="check" v-if="currentLocale === lang.code" />
              </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>

        <!-- 用户下拉框 -->
        <q-btn-dropdown flat color="amber-12" icon="person" class="user-btn">
          <q-list>
            <q-item>
              <q-item-section>
                <q-item-label>{{ t('rt.currentAddress') }}</q-item-label>
              </q-item-section>
              <q-item-section side>
                <q-item-label caption>{{ loginInfoStore.loginInfo.username }}@{{
                    loginInfoStore.loginInfo.rcs2ServerUrl
                  }}
                </q-item-label>
              </q-item-section>
            </q-item>

            <q-item clickable v-close-popup @click="checkForUpdates">
              <q-item-section avatar>
                <q-icon name="update" />
              </q-item-section>
              <q-item-section>{{ t('rt.checkUpdates') }}</q-item-section>
              <q-item-section side>
                <q-item-label caption>{{ getAppVersion() }}</q-item-label>
              </q-item-section>
            </q-item>

            <q-separator />

            <q-item clickable v-close-popup @click="toggleFullscreen">
              <q-item-section avatar>
                <q-icon name="fullscreen" />
              </q-item-section>
              <q-item-section>{{ fullscreenText }}</q-item-section>
            </q-item>

            <q-item clickable v-close-popup @click="refresh">
              <q-item-section avatar>
                <q-icon name="refresh" />
              </q-item-section>
              <q-item-section>{{ t('refresh') }}</q-item-section>
            </q-item>

            <q-separator />
            <q-item clickable v-close-popup @click="logout">
              <q-item-section avatar>
                <q-icon name="logout" />
              </q-item-section>
              <q-item-section>{{ t('rt.logout') }}</q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>

      </q-toolbar>
    </q-header>

    <q-page-container>
      <q-page class="content-page">
        <!-- AGV调度页签 -->
        <router-view />
      </q-page>
    </q-page-container>

    <!-- 版本检查对话框 -->
    <CheckForUpdates v-model="showUpdatesDialog" />
  </q-layout>
</template>
<style lang="less" scoped>
.yv-header-bg {
  background: #545c64 !important;

  .q-btn {
    padding: 4px 8px;
  }
}

.q-tabs.yv-header-tab {
  background: none;

  .q-tab:not(.q-tab--active) {
    color: #fff;
  }
}

:deep(.yv-header-tab .q-hoverable:hover > .q-focus-helper) {
  background: #434a50;
  opacity: 1;

  &:after {
    background: none;
  }
}

//.content-page {
//  height: 100vh;
//}

.full-height {
  height: 100%;
}

.full-width {
  width: 100%;
}

.language-btn,
.user-btn {
  margin-left: 8px;
}

.q-tabs {
  background: rgba(255, 255, 255, 0.1);
}

.q-tab-panels {
  height: calc(100vh - 50px);
}

.q-tab-panel {
  height: 100%;
  padding: 0;
}

iframe {
  border: none;
  width: 100%;
  height: 100%;
}

.q-pa-lg {
  background: #f5f7fa;
}
</style>

